<template>
  <section class="todoapp">
    <TodoHeader @addList="addList"></TodoHeader>
    <TodoBody
      :list="renderList"
      :isCheckedNum="isCheckedNum"
      @changeStatues="changeStatues"
      @delList="delList"
      @isAllchecked="isAllchecked"
    ></TodoBody>
    <TodoFooter
      :selectNum="selectNum"
      v-model="type"
      :type="type"
      @selectList="selectList"
      @allDone="allDone"
      v-show="list.length"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoBody from './components/TodoBody.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  components: {
    TodoHeader,
    TodoBody,
    TodoFooter,
  },
  data() {
    return {
      type: 'all',
      list: JSON.parse(localStorage.getItem('TodoList')),
    }
  },
  methods: {
    //改变状态
    changeStatues(id) {
      const res = this.list.find((item) => item.id === id)
      res.isDone = !res.isDone
    },
    //删除
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    //添加
    addList(name) {
      const obj = {
        id: +new Date(),
        name: name,
        isDone: false,
      }
      if (!name.length) return
      this.list.push(obj)
    },
    selectList(type) {
      this.type = type
    },
    allDone() {
      this.list = this.list.filter((item) => item.isDone === false)
    },
    isAllchecked(flag) {
      this.list.forEach((item) => (item.isDone = flag))
    },
  },
  computed: {
    selectNum() {
      return this.list.filter((item) => item.isDone === false).length
    },

    renderList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => item.isDone === false)
        case 'completed':
          return this.list.filter((item) => item.isDone === true)
        default:
          return this.list
      }
    },
    isCheckedNum() {
      return this.list.every((item) => item.isDone)
    },
  },
  watch: {
    list: {
      deep: true,
      handler(value) {
        localStorage.setItem('TodoList', JSON.stringify(value))
      },
    },
  },
}
</script>

<style></style>
